﻿using System;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZSZ.DTO;
using ZSZ.IService;
using ZSZ.Model;
using ZSZ.Common;

namespace ZSZ.Service
{
    public partial class UserService : BaseService<User>, IUserService
    {
        #region 查询
        private IQueryable<User> GetJoinAll()
        {
            return GetAll().Include(u => u.City).AsNoTracking();
        }

        public UserDTO GetByPhoneNum(string phoneNum)
        {
            var users = GetJoinAll().Where(u => u.PhoneNum == phoneNum);
            var count = users.Count();
            if (count <= 0)
            {
                return null;
            }
            else if (count == 1)
            {
                return ToDTO(users.Single());
            }
            else
            {
                throw new Exception("获取到多个手机号码为：" + phoneNum + "的用户");
            }
        }

        private UserDTO ToDTO(User user)
        {
            UserDTO dto = new UserDTO();
            dto.CreateDateTime = user.CreateDateTime;
            dto.Id = user.Id;
            dto.PhoneNum = user.PhoneNum;
            dto.PasswordHash = user.PasswordHash;
            dto.LoginErrorTimes = user.LoginErrorTimes;
            dto.LastLoginErrorDateTime = user.LastLoginErrorDateTime;
            dto.CityId = user.CityId;
            if (user.City != null)
            {
                dto.CityName = user.City.Name;
            }
            else
            {
                dto.CityName = "";
            }
            return dto;
        }

        public bool IsLocked(long id)
        {
            var user = GetById(id);
            //错误登录次数>=5，最后一次登录错误时间在30分钟之内
            return (user.LoginErrorTimes >= 5
                && user.LastLoginErrorDateTime > DateTime.Now.AddMinutes(-30));
        }

        public bool CheckLogin(string phoneNum, string password)
        {
            var user = GetAll().SingleOrDefault(u => u.PhoneNum == phoneNum);
            if (user == null)
            {
                return false;
            }
            else
            {
                string dbPwdHash = user.PasswordHash;
                string salt = user.PasswordSalt;
                //MD5(MD5(用户名+用户输入密码+salt))
                string userPwdHash = CommonHelper.CalcMD5(CommonHelper.CalcMD5(user.PhoneNum + password + salt));
                return dbPwdHash == userPwdHash;
            }

        }
        #endregion

        public long Add(string phoneNum, string password)
        {
            string passwordSalt = CommonHelper.GenerateCaptchaCode(6);
            User user = new User();
            user.PhoneNum = phoneNum;
            user.PasswordSalt = passwordSalt;
            //MD5(MD5(用户名+用户输入密码+salt))
            user.PasswordHash = CommonHelper.CalcMD5(CommonHelper.CalcMD5(phoneNum + password + passwordSalt));
            Add(user);
            return user.Id;
        }

        public void SetUserCityId(long userId, long cityId)
        {
            var user = GetById(userId);
            if (user == null)
            {
                throw new ArgumentException("用户id不存在" + userId);
            }
            user.CityId = cityId;
            Update(user);
        }

        public void UpdatePwd(long userId, string newPassword)
        {
            string passwordSalt = CommonHelper.GenerateCaptchaCode(6);
            var user = GetById(userId);
            if (user == null)
            {
                throw new ArgumentException("用户id不存在" + userId);
            }
            user.PasswordSalt = passwordSalt;
            //MD5(MD5(用户名+用户输入密码+salt))
            user.PasswordHash = CommonHelper.CalcMD5(CommonHelper.CalcMD5(user.PhoneNum + newPassword + passwordSalt));
            Update(user);
        }

        /// <summary>
        /// 登录失败
        /// </summary>
        /// <param name="id"></param>
        public void IncrLoginError(long id)
        {

            //检查手机号不能重复
            var user = GetById(id);
            if (user == null)
            {
                throw new ArgumentException("用户不存在 " + id);
            }
            user.LoginErrorTimes++;
            user.LastLoginErrorDateTime = DateTime.Now;
            Update(user);

        }
        /// <summary>
        /// 登录成功
        /// </summary>
        /// <param name="id"></param>
        public void ResetLoginError(long id)
        {
            //检查手机号不能重复
            var user = GetById(id);
            if (user == null)
            {
                throw new ArgumentException("用户不存在 " + id);
            }
            user.LoginErrorTimes = 0;
            user.LastLoginErrorDateTime = null;
            Update(user);
        }
    }
}
